<template>
  <div class="batch-import">
    <el-drawer
      v-model="visible"
      :title="props.title"
      :size="props.width"
      :before-close="hide"
      :close-on-click-modal="true"
      :close-on-press-escape="false"
      :append-to-body="true"
      :modal="true"
      :modal-append-to-body="true"
      destroy-on-close
    >
      <template #title>
        <div class="flex flex-col">
          <div class="drawer-header">
            <div class="flex items-center dot" v-if="showDot">
              <div class="w-[5px] h-[5px] rounded-1/2 bg-[#3721FF]"></div>
              <span class="ml-2 drawer-title">{{ props.title }}</span>
            </div>
          </div>
          <div class="text-[12px] mt-[4px] text-[#999] desc">{{ props.titleDesc }}</div>
        </div>
      </template>
      <div class="drawer-content">
        <div class="w-full h-[1px] bg-[#efefef] mb-[30px] line"></div>
        <slot></slot>
        <div class="flex flex-col download bg-[#FAFAFA] p-6 rounded-lg">
          <h3>1.下载导入模板</h3>
          <span class="text-[#999999] text-[12px] pt-10px pb-20px">请根据提示信息完善表格内容</span>
          <el-button plain class="w-[120px]" style="height: 42px" @click="downTeamplate">
            <Icon icon="ep:download" color="#3721FF" />
            <span class="text-[#3721FF]">下载模板</span>
          </el-button>
        </div>
        <div class="flex flex-col download bg-[#FAFAFA] p-6 rounded-lg mt-8">
          <h3>2.上传完善后的模板</h3>
          <span class="text-[#999999] text-[12px] pt-10px">
            更新信息的模板中，如有空的数据列，则相应字段信息会被清空，请谨慎填写；
          </span>
          <span class="text-[#3721FF] text-[12px] pt-10px pb-20px">
            模板中表头名称不可更改，表头行不能删除。
          </span>
          <div class="flex items-center mb-[20px] depat" v-if="showDept">
            <div class="flex items-center items">
              <div class="label">创建部门：</div>
              <div class="w-[150px] val">
                <el-tree-select
                  v-model="deptId"
                  :data="props.deptList"
                  :render-after-expand="false"
                  clearable
                  check-strictly
                  @change="handleChange"
                />
              </div>
            </div>
            <div class="flex items-center ml-[20px] items">
              <div class="label">创建者：</div>
              <div class="w-[150px] val">
                <el-select
                  v-model="creator"
                  :placeholder="`请选择人员`"
                  class="custom-select"
                  clearable
                  filterable
                  @change="handleCreatorChange"
                >
                  <el-option
                    v-for="option in createList"
                    :key="option.label"
                    :label="option.label"
                    :value="option.value"
                  />
                </el-select>
              </div>
            </div>
          </div>
          <div class="flex items-center mb-[20px] depat" v-if="showStatusList">
            <div class="flex items-center ml-[20px] items">
              <div class="label">状态：</div>
              <div class="w-[150px] val">
                <el-select
                  v-model="statusValue"
                  :placeholder="`请选择状态`"
                  class="custom-select"
                  clearable
                  @change="handleCreatorChange"
                >
                  <el-option
                    v-for="option in statusList"
                    :key="option.label"
                    :label="option.label"
                    :value="option.value as Number"
                  />
                </el-select>
              </div>
            </div>
          </div>
          <div
            class="bg-white border-dashed rounded-lg border-1px border-[#D9D9D9]"
            @dragover.prevent
            @drop.prevent="handleDrop"
            @click="triggerFileInput"
          >
            <div class="flex flex-col items-center justify-center h-[200px]" v-if="!selectedFile">
              <input
                type="file"
                ref="fileInput"
                @change="handleFileChange"
                accept=".xls,.xlsx"
                class="hidden"
              />
              <img
                class="w-[80px] h-auto"
                src="https://img.alicdn.com/imgextra/i3/1034622205/O1CN01ANJ0x81S9wOlOwBiH_!!1034622205.png"
                alt=""
              />
              <p class="text-[#101010] text-[14px] pt-10px">
                将文件拖拽至此区域，或 <span class="text-[#3721FF] cursor-pointer">点击添加</span>
              </p>
              <span class="text-[#999999] text-[12px]">支持 .xls,.xlsx 格式，限10M以内</span>
            </div>
            <!-- 显示文件信息 -->
            <div v-if="selectedFile" class="flex mt-4 items-center text-center px-[15px] h-[200px]">
              <div class="flex justify-between w-full">
                <div class="flex items-center info">
                  <p class="text-[#101010] text-[14px]">已选择文件:</p>
                  <p class="text-[#3721FF] max-w-[200px] text-cut ml-[15px] text-[14px]">
                    {{ selectedFile.name }}
                  </p>
                  <p class="text-[#999999] ml-[15px] text-[12px]"
                    >大小: {{ formatFileSize(selectedFile.size) }}</p
                  >
                </div>
                <div class="cursor-pointer action">
                  <Icon icon="ep:delete" color="#f00" @click.stop="clearFile" />
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="flex flex-col mt-8">
          <h4>导入规则</h4>
          <p class="pt-10px pb-10px">
            1.请先下载模版，在模版中按要求填写组织信息，然后上传该文件
          </p>
          <p>2.单个文件不能超过10M，单次导入数据不能超过5000条</p>
        </div>
      </div>
      <template #footer>
        <div class="el-dia-btn">
          <el-button @click="hide">取消</el-button>
          <el-button type="primary" color="#3721FF" @click="confirm">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { DictDataType } from '@/utils/dict'
const message = useMessage() // 消息弹窗
defineOptions({ name: 'BatchImport' })
const visible = ref(false)
interface selectVO {
  label: string
  value: number | string
}

const props = defineProps({
  showDot: {
    type: Boolean,
    default: false
  },
  isBatchImport: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '批量导入'
  },
  titleDesc: {
    type: String,
    default: ''
  },
  // 宽度
  width: {
    type: String,
    default: '50%'
  },
  showDept: {
    type: Boolean,
    default: false
  },
  deptList: {
    type: Array,
    default: () => []
  },
  createList: {
    type: Array as () => selectVO[],
    default: () => []
  },
  statusList: {
    type: Array as () => DictDataType[],
    dfault: () => []
  },
  showStatusList: {
    type: Boolean,
    default: false
  }
})

const fileInput = ref<HTMLInputElement | null>(null)

const selectedFile = ref<File | null>(null)

const deptId = ref()

const createName = ref()

const creator = ref()

const statusValue = ref<number>()

const emit = defineEmits(['close', 'confirm', 'changeDept', 'downTeamplate'])
const confirm = () => {
  if (!selectedFile.value) {
    message.error('请选择文件')
    return
  }
  if (props.showDept) {
    if (!createName.value) {
      message.error('请选择创建者')
      return
    }
    if (!deptId.value) {
      message.error('请选择创建部门')
      return
    }
  }
  if (props.showStatusList) {
    if (!statusValue.value) {
      message.error('请选择状态')
      return
    }
  }
  emit(
    'confirm',
    props.showDept
      ? {
          deptId: deptId.value,
          createName: createName.value,
          creator: creator.value,
          file: selectedFile.value
        }
      : props.showStatusList
        ? {
            statusValue: statusValue.value,
            file: selectedFile.value
          }
        : { file: selectedFile.value }
  )
  selectedFile.value = null
  hide()
}

const triggerFileInput = () => {
  if (fileInput.value) {
    // 检查 fileInput.value 是否为 null
    fileInput.value.click() // 触发文件输入框的点击事件
  }
}

/**
 * 点击选择文件
 */
const handleFileChange = (event: Event) => {
  const files = (event.target as HTMLInputElement).files
  if (files && files.length > 0) {
    selectedFile.value = files[0] // 保存选中的文件
  }
}
/**
 * 拖拽文件
 */
const handleDrop = (event: DragEvent) => {
  const files = event.dataTransfer?.files
  if (files && files.length > 0) {
    selectedFile.value = files[0] // 保存选中的文件
  }
}

const clearFile = async () => {
  try {
    await message.delConfirm()
    selectedFile.value = null
  } catch {
    return
  }
}

/**
 * 选择人员后获取人员昵称
 */
const handleCreatorChange = () => {
  createName.value = props.createList.find((item) => item.value === creator.value)?.label
}

/**
 * 点击下载模板
 */
const downTeamplate = () => {
  emit('downTeamplate')
}

/**
 * 选择部门
 */
const handleChange = () => {
  emit('changeDept', deptId.value)
}

// 格式化文件大小
const formatFileSize = (size: number) => {
  const kb = size / 1024
  const mb = kb / 1024
  if (mb >= 1) {
    return `${mb.toFixed(2)} MB`
  }
  return `${kb.toFixed(2)} KB`
}

const show = () => {
  visible.value = true
}
const hide = () => {
  visible.value = false
  emit('close')
}
watch(
  () => props.isBatchImport,
  (val) => {
    visible.value = val
  }
)

defineExpose({
  show,
  hide
})
</script>

<style scoped>
@import '@/styles/website.scss';
:deep(.el-drawer__header) {
  margin-bottom: 0px !important;
}
</style>
